const ctxutil = require('ym_ctx_util');
const Joi = require("joi");
// 保存投放商品信息
/**
 * @description:  创建投放商品
 * @param {object} ctx 上下文
 * @param {string} name 商品名称
 * @param {string} item_id 商品itemid
 * @param {string} url 投放地址
 * @param {string} state 解绑 0 绑定1
 * @param {string} operation_state  操作状态 0 操作中 1 操作成功 2 操作失败
 * @param {string} create_date 创建时间
 * @param {string} update_date 修改时间
 * @return {*}
 * @author: ljr
 */
exports.savePutGood = async (ctx) => {
    await ctxutil.apply(ctx);
    const { cloud, data: { name, item_id, state, url } } = ctx;
    try {
        let result = await itemsBind(cloud, item_id, state, url);


        let res = await ctx.mfutil.db.mongo.insertOne('put_good', {
            name,
            item_id,
            url,
            state,
            operation_state: result ?  "1" :  "2" ,
            create_date: await ctx.mfutil.common.curentTime(),
            update_date: await ctx.mfutil.common.curentTime(),
        });
        await ctx.mfutil.logger.info(`创建投放商品：${JSON.stringify(res)}`);
        return await ctx.mfutil.common.basicode(0, res);
    } catch (e) {
        console.log("eeee", e);
        return await ctx.mfutil.common.basicode(e.code || 8000, e);
    }
};

// 修改投放商品
exports.updatePutGood = async (ctx) => {
    await ctxutil.apply(ctx);
    const { cloud, data: { id, name, item_id, state, url } } = ctx;
    console.log(ctx.data);

    try {
        let result = await itemsBind(cloud, item_id, state, url);
        let res = await ctx.mfutil.db.mongo.updateMany('put_good', { _id: id }, {
            $set: {
                name,
                item_id,
                url,
                state,
                operation_state: result ?  "1" :  "2" ,
                update_date: await ctx.mfutil.common.curentTime(),
            }
        });
        return await ctx.mfutil.common.basicode(0, res);
    } catch (e) {
        return await ctx.mfutil.common.basicode(e.code || 8000, e);
    }
};

//删除投放商品，解绑商品才能删除。
exports.delPutGood = async (ctx) => {
    await ctxutil.apply(ctx);
    const { data: { id } } = ctx;
    try {
        let res = await ctx.mfutil.db.mongo.deleteMany('put_good', { '_id': id });
        return await ctx.mfutil.common.basicode(0, res);
    } catch (e) {
        return await ctx.mfutil.common.basicode(e.code || 8000, e);
    }
};

//分页查询投放商品信息
exports.pageList = async (ctx) => {
    // 初始化
    await ctxutil.apply(ctx);
    try {
        const schema = Joi.object().keys({
            page: Joi.number().required(),    //  页码
            pagesize: Joi.number().required(), //  每页数量
            select_name: Joi.string(),
            select_item_id: Joi.string(),
            select_state: Joi.string(),
            select_operation_state: Joi.string(),
        });

        let validate = schema.validate(ctx.data);
        if (validate.error) {
            return await ctx.mfutil.common.basicode(7000, {}, validate);
        }
        let filter = {};

        if (ctx.data.select_name && JSON.stringify(ctx.data) !== '{}') {
            filter.name = { $regex: ctx.data.select_name, $options: "$i" }
        }
        if (ctx.data.select_item_id && JSON.stringify(ctx.data) !== '{}') {
            filter.item_id = { $regex: ctx.data.select_item_id, $options: "$i" }
        }
        if (ctx.data.select_state && JSON.stringify(ctx.data) !== '{}') {
            filter.state = ctx.data.select_state
        }
        if (ctx.data.select_operation_state && JSON.stringify(ctx.data) !== '{}') {
            filter.operation_state = ctx.data.select_operation_state
        }
        // 手镯查询
        const total = await ctx.cloud.db.collection("put_good").count(filter);


        if (!total) return await ctx.mfutil.common.basicode(0, { total: total, list: [] });

        let num = ctx.data.pagesize * (ctx.data.page - 1);
        const res = await ctx.cloud.db.collection("put_good").find(filter,
            {
                sort: { "update_date": -1 },
                limit: ctx.data.pagesize,
                skip: num,
            }
        );
        return await ctx.mfutil.common.basicode(0, { total: total, list: res });
    } catch (e) {
        return await ctx.mfutil.common.basicode(e.code || 8000, e);
    }
}

//绑定/解绑
let itemsBind = (cloud, item_id, state, url) => {
    return new Promise(async (reslove, reject) => {
        try {
            const result = await cloud.topApi.invoke({
                api: 'taobao.miniapp.distribution.items.bind',
                data: {
                    'target_entity_list': item_id,
                    'url': url,
                    'add_bind': state === "1" ? 'true' : 'false'
                },
                autoSession: true,
            });
            console.log("itemsBind::::res~~~~~~~~~~~~~", result);
            if (result.model_list.distribution_order_bind_target_entity_open_result_dto[0].bind_result_list.distribution_order_bind_base_dto[0].success) {
              reslove(true);
            }else {
              reslove(false);
            }
        } catch (error) {
            reject(error)
        }
    })

}